package com.aizhixin.lab.task.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import com.aizhixin.lab.config.Config;
import com.aizhixin.lab.course.template.service.UploadService;
import com.aizhixin.lab.task.core.ExerciseType;
import com.aizhixin.lab.task.domain.ImportTaskDomain;
import com.aizhixin.lab.task.domain.SaveDomain;
import com.aizhixin.lab.task.entity.Task;
import com.aizhixin.lab.task.service.TaskService;
import jxl.Workbook;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.account.service.AccountService;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.utils.TokenUtil;
import com.aizhixin.lab.task.domain.TaskQuestionDomain;
import com.aizhixin.lab.task.entity.TaskQuestion;
import com.aizhixin.lab.task.service.TaskQuestionsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/v1/task")
@Api(value = "任务库试题操作", description = "任务库试题操作")
public class TaskQuestionsController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskQuestionsService questionsService;
	@Autowired
	private Config config;
    @Autowired
    private UploadService uploadService;
    @RequestMapping(value = "/savequestions", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "保存任务试题", httpMethod = "POST", notes = "保存任务试题<br><br><b>@author zhengning</b>")
    public ResponseEntity<?> saveQuestions(@RequestHeader("Authorization") String token,
                                           @ApiParam(value = "<b>必填</b><br>workLibId:任务库id<br>content:题干<br>analysis:解析<br>answer:正确答案<br>questionType：试题类型(10:单选题,20:多选题,30:判断题,40:论述题,50:计算题,60:编程题,70:简答题,80:画图题,90:其他)<br>choiceList:试题客观题选项集合(客观题必填)<br><b>选填：</b><br>language：编程题语言（如：java）<br>") @RequestBody TaskQuestionDomain domain) {
        Map<String, Object> result = new HashMap<String, Object>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        if (domain.getTaskId().isEmpty()) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "任务id不能为空！");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        boolean isFileEmpty = false;
        if (domain.getAccessorylist().isEmpty()) {
            isFileEmpty = true;
        }
        if (domain.getQuestionContent().isEmpty() && !isFileEmpty) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "题目题干和题干附件不能同时为空！");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        if((ExerciseType.MULTIPLE.getIntValue().equals(domain.getQuestionType()) || ExerciseType.SINGLE.getIntValue().equals(domain.getQuestionType()))&&domain.getChoicelist()==null){
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "客观题选项不能够为空！");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        if (StringUtils.isEmpty(domain.getAnswer())){
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "答案不能为空！");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        Task byId = taskService.findById(domain.getTaskId());
        if (byId==null){
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "任务不存在");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }

        //如果题目类型为编程题选择题则必须传语言类型
        if (domain.getQuestionType() == 60 && domain.getLanguage() == null){
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "语言种类必须选择！");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        //如果题目类型为简答题则必须设置关键字
        if (domain.getQuestionType() == 70 && domain.getKeyword() == null){
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "关键字必须设置！");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        TaskQuestion questions = questionsService.saveQuestions(domain, account);
        taskService.updateQuestionNum(domain.getTaskId());
        result.put(ApiReturnConstants.DATA, questions);
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }


    @RequestMapping(value = "/saveQuestionList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "保存任务试题", httpMethod = "POST", notes = "保存任务试题<br><br><b>@author lwq</b>")
    public ResponseEntity<?> saveQuestionList(@RequestHeader("Authorization") String token,
                                           @ApiParam(value = "<b>必填</b><br>workLibId:任务库id<br>content:题干<br>analysis:解析<br>answer:正确答案<br>questionType：试题类型(10:单选题,20:多选题,30:判断题,40:论述题,50:计算题,60:编程题,70:简答题,80:画图题,90:其他)<br>choiceList:试题客观题选项集合(客观题必填)<br><b>选填：</b><br>language：编程题语言（如：java）<br>") @RequestBody SaveDomain domain) {
        Map<String, Object> result = new HashMap<String, Object>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }

        result = questionsService.saveQuestionList(domain.getDomain(), account);
        if (domain.getDomain().size()>0){
            TaskQuestionDomain taskQuestionDomain = domain.getDomain().get(0);
            if (taskQuestionDomain.getTaskId()!=null&&"".equals(taskQuestionDomain.getTaskId())){
                taskService.updateQuestionNum(taskQuestionDomain.getTaskId());
            }
        }
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/ployv", method = RequestMethod.GET)
    @ApiOperation(value = "获取polyvWriteToken", httpMethod = "GET", notes = "获取polyvWriteToken<br><br><b>@author lwq</b>")
    public ResponseEntity<?> getPolyvToken(@RequestHeader("Authorization") String token) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        String polyvToken = uploadService.getPolyvWriteToken();
        return new ResponseEntity<>(polyvToken, HttpStatus.OK);
    }
    @RequestMapping(value = "/getPolyvReadToken", method = RequestMethod.GET)
    @ApiOperation(value = "获取polyvReadToken", httpMethod = "GET", notes = "获取polyvReadToken<br><br><b>@author lwq</b>")
    public ResponseEntity<?> getPolyvWriteToken(@RequestHeader("Authorization") String token) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        String polyvToken = uploadService.getPolyvReadToken();
        return new ResponseEntity<>(polyvToken, HttpStatus.OK);
    }
        @RequestMapping(value = "/updatequestions", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "修改任务试题", httpMethod = "PUT", notes = "修改任务试题<br><br><b>@author zhengning</b>")
    public ResponseEntity<?> updateQuestions(@RequestHeader("Authorization") String token,
                                             @ApiParam(value = "<b>必填</b><br>Id:试题id<br>content:题干<br>analysis:解析<br>answer:正确答案<br>answer:正确答案<br>questionType：试题类型(10:单选题,20:多选题,30:判断题,40:论述题,50:计算题,60:编程题,70:简答题,80:画图题,90:其他)<br>language：编程题语言（如：java）<br>choiceList:试题客观题选项集合(客观题必填)") @RequestBody TaskQuestionDomain domain) {
        Map<String, Object> result = new HashMap<String, Object>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        if (domain.getId().isEmpty()) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "题目id不能为空！");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        boolean isFileEmpty = false;
        if (domain.getAccessorylist().isEmpty()) {
            isFileEmpty = true;
        }
        if (domain.getQuestionContent().isEmpty() && !isFileEmpty) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "题目题干和题干附件不能同时为空！");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        TaskQuestion questions = questionsService.findById(domain.getId());
        if (null == questions) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "试题不存在！");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        questions = questionsService.updateQuestions(domain, account, questions);
        result.put(ApiReturnConstants.DATA, questions.getId());
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ApiOperation(value = "上传文件", httpMethod = "POST", notes = "上传文件<br><br><b>@author lwq</b>")
    public ResponseEntity<?> uploadFile(@RequestHeader("Authorization") String token,
                                        @ApiParam(value = "文件", required = true) @RequestParam(value = "file") MultipartFile file) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }

        List<TaskQuestionDomain> list=new ArrayList<>();
        String filePath="";
        try {
            String s = UUID.randomUUID().toString().replaceAll("-", "");
            String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            filePath=config.getBaseDir() + "/" + s+substring;
            File dest = new File(filePath);
            FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ResponseEntity(filePath, HttpStatus.OK);
    }
    @RequestMapping(value = "/getQiNiuYunToken", method = RequestMethod.POST)
    @ApiOperation(value = "获取七牛云的token验证", httpMethod = "POST", notes = "获取七牛云的token验证<br><br><b>@author lwq</b>")
    public ResponseEntity<?> uploadFileTest(@RequestHeader("Authorization") String token)  {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }

        String uploadToken = uploadService.getUploadToken();
        return new ResponseEntity(uploadToken, HttpStatus.OK);
    }
    @RequestMapping(value = "/qiniu", method = RequestMethod.POST)
    @ApiOperation(value = "文件上传到七牛云", httpMethod = "POST", notes = "上传文件<br><br><b>@author lwq</b>")
    public ResponseEntity<?> uploadF(@RequestHeader("Authorization") String token,
                                        @ApiParam(value = "文件", required = true) @RequestParam(value = "file") MultipartFile file) {
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
        }

        String s = uploadService.uploadFile(file);
        return new ResponseEntity(s, HttpStatus.OK);
    }
    @RequestMapping(value = "/findQuestionByOrderNum", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询单个任务试题", httpMethod = "GET", notes = "查询单个任务试题<br><br><b>@author lwq</b>")
    public ResponseEntity<?> findQuestionByOrderNum(@RequestHeader("Authorization") String token,
                                           @ApiParam(value = "taskId 任务id") @RequestParam(value = "taskId", required = true) String taskId,
                                                    @ApiParam(value = "orderNum 题号") @RequestParam(value = "orderNum", required = true) Integer orderNum) {
        Map<String, Object> result = new HashMap<String, Object>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        if (StringUtils.isEmpty(taskId)) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "任务id不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        if (orderNum==0||orderNum==null){
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "题号不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        TaskQuestionDomain questionOne = questionsService.findQuestionOne(taskId, orderNum);
        result.put(ApiReturnConstants.DATA, questionOne);
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/findTaskQuestionById", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询任务试题", httpMethod = "GET", notes = "查询任务试题<br><br><b>@author zhengning</b>")
    public ResponseEntity<?> findTaskQuestionById(@RequestHeader("Authorization") String token,
                                           @ApiParam(value = "taskQuestionId 试题id") @RequestParam(value = "taskQuestionId", required = true) String taskQuestionId) {
        Map<String, Object> result = new HashMap<String, Object>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        if (StringUtils.isEmpty(taskQuestionId)) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "任务试题id不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        TaskQuestionDomain questionById = questionsService.findQuestionById(taskQuestionId);
        result.put(ApiReturnConstants.DATA, questionById);
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }
    @RequestMapping(value = "/findQuestions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "查询任务试题", httpMethod = "GET", notes = "查询任务试题<br><br><b>@author zhengning</b>")
    public ResponseEntity<?> findQuestions(@RequestHeader("Authorization") String token,
                                           @ApiParam(value = "taskId 任务id") @RequestParam(value = "taskId", required = true) String taskId) {
        Map<String, Object> result = new HashMap<String, Object>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        if (StringUtils.isEmpty(taskId)) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "任务id不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        List<TaskQuestionDomain> questionsDomainlist = questionsService.findByTaskId(taskId);
        result.put(ApiReturnConstants.DATA, questionsDomainlist);
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/exportQuestions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导出任务试题", httpMethod = "GET", notes = "导出任务试题<br><br><b>@author lwq</b>")
    public ResponseEntity<?> exportQuestions(@ApiParam(value = "taskId 任务id") @RequestParam(value = "taskId", required = false) String taskId,
                                             HttpServletResponse response) throws IOException {
        Map<String, Object> result = new HashMap<String, Object>();
        if (StringUtils.isEmpty(taskId)) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "任务id不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }

        Task task = taskService.findById(taskId);
        List<TaskQuestionDomain> questionsDomainList = questionsService.findByTaskId(taskId);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("任务模板");
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("试题类型(10:单选题,20:多选题,30:判断题,60:编程题,70:简答题,90:其他)");
        row.createCell(1).setCellValue("试题序号");
        row.createCell(2).setCellValue("题干");
        row.createCell(3).setCellValue("解析");
        row.createCell(4).setCellValue("正确答案");
        row.createCell(5).setCellValue("选择题选项数");
        for (int i = 0; i < questionsDomainList.size(); i++) {
            HSSFRow row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(questionsDomainList.get(i).getQuestionType());
            row1.createCell(1).setCellValue(questionsDomainList.get(i).getOrderNum());
            row1.createCell(2).setCellValue(questionsDomainList.get(i).getQuestionContent().replace("<p>","").replace("</p>","").replaceAll("<strong>","").replaceAll("</strong>","").replaceAll("&nbsp;",""));
            row1.createCell(3).setCellValue(questionsDomainList.get(i).getAnalysis().replace("<p>","").replace("</p>","").replaceAll("<strong>","").replaceAll("</strong>","").replaceAll("&nbsp;",""));
            row1.createCell(4).setCellValue(questionsDomainList.get(i).getAnswer().replace("<p>","").replace("</p>","").replaceAll("<strong>","").replaceAll("</strong>","").replaceAll("&nbsp;",""));
            row1.createCell(5).setCellValue(questionsDomainList.get(i).getChoicelist().size());
            for (int j = 0; j < questionsDomainList.get(i).getChoicelist().size(); j++) {
                row1.createCell(j + 6).setCellValue(questionsDomainList.get(i).getChoicelist().get(j).getChoiceContent().replace("<p>","").replace("</p>","").replaceAll("<strong>","").replaceAll("</strong>","").replaceAll("&nbsp;",""));
            }
        }

        FileOutputStream output = new FileOutputStream(config.getBaseDir()+"/"+task.getTaskName()+".xls");
        wb.write(output);
        output.flush();
        String basePath =config.getBaseDir()+ "/" +task.getTaskName()+".xls";
        File file = new File(basePath);
        // 取得文件名。
        String filename = file.getName().toString();

        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(basePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(System.currentTimeMillis() + ".xls", "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();

        return new ResponseEntity(questionsDomainList, HttpStatus.OK);

    }

    @RequestMapping(value = "/importTask", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "导入任务试题", httpMethod = "POST", notes = "导入任务试题<br><br><b>@author lwq</b>")
    public ResponseEntity<?> importTask(@RequestHeader("Authorization") String token,
                                        @ApiParam(value = "importTaskDomain") ImportTaskDomain domain,
                                        @ApiParam(value = "Excel数据文件", required = true) @RequestParam(value = "file") MultipartFile file) {
		AccountDTO account = accountService.getUserByToken(token);
		if (account == null) {
			return new ResponseEntity<Object>(TokenUtil.tokenValid(), HttpStatus.UNAUTHORIZED);
		}
		List<TaskQuestionDomain> list=new ArrayList<>();
			try {
				File dest = new File(config.getBaseDir() + "/" + file.getOriginalFilename());
				FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
				list=taskService.fileTransformList(dest);
                if (dest!=null){
                    dest.delete();
                }
			} catch (Exception e) {
				e.printStackTrace();
			}
		Task task = taskService.save(domain, account, list.size());
		List list1 = taskService.saveQuestionAndAnswer(list, task, account);
		return new ResponseEntity(list1, HttpStatus.OK);
    }


//	@RequestMapping(value = "/findquestions/workRelease", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
//	@ApiOperation(value = "查询发布试题", httpMethod = "GET", notes = "查询发布试题<br><br><b>@author likai</b>")
//	public ResponseEntity<?> findQuestionsWorkRelease(@RequestHeader("Authorization") String token,
//																										 @ApiParam(value = "workLibId 任务库id") @RequestParam(value = "workReleaseId") String workReleaseId){
//		AccountDTO dto = authUtilService.getSsoUserInfo(token);
//		if (null == dto || null == dto.getId()) {
//			throw new ExceptionAuth(401,"无权限");
//		}
//		if (null == workReleaseId || "".equals(workReleaseId)) {
//		    throw new ExceptionValidation(417,"发布id不能为空");
//		}
//		return questionsService.findWorkReleaseInfo(workReleaseId);
//
//	}

    @RequestMapping(value = "/upquestions", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "上移任务试题", httpMethod = "PUT", notes = "上移任务试题<br><br><b>@author likai</b>")
    public ResponseEntity<?> upQuestions(@RequestHeader("Authorization") String token,
                                         @ApiParam(value = "questionsId 试题id") @RequestParam(value = "questionsId", required = true) String questionsId) {
        Map<String, Object> result = new HashMap<String, Object>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        if (null == questionsId || "".equals(questionsId)) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "试题id不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        TaskQuestion questions = questionsService.findById(questionsId);
        if (null == questions) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "试题不存在");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        if (1 == questions.getOrderNum()) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "试题已经是第一道不能上移");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        questions = questionsService.upQuestions(result, questions);
        if (null == questions) {
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        } else {
            result.put(ApiReturnConstants.DATA, questions.getId());
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
    }

    @RequestMapping(value = "/downquestions", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "下移任务试题", httpMethod = "PUT", notes = "下移任务试题<br><br><b>@author zhengning</b>")
    public ResponseEntity<?> downQuestions(@RequestHeader("Authorization") String token,
                                           @ApiParam(value = "questionsId 试题id") @RequestParam(value = "questionsId", required = true) String questionsId) {
        Map<String, Object> result = new HashMap<String, Object>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        if (null == questionsId || "".equals(questionsId)) {
            result.put(ApiReturnConstants.RESULT, Boolean.FALSE);
            result.put(ApiReturnConstants.CAUSE, "试题id不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        TaskQuestion questions = questionsService.findById(questionsId);
        if (null == questions) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "试题不存在");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        questions = questionsService.downQuestions(result, questions);
        if (null == questions) {
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        } else {
            result.put(ApiReturnConstants.DATA, questions.getId());
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
    }

    @RequestMapping(value = "/delquestions", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "删除任务试题", httpMethod = "DELETE", notes = "删除任务试题<br><br><b>@author zhengning</b>")
    public ResponseEntity<?> delQuestions(@RequestHeader("Authorization") String token,
                                          @ApiParam(value = "questionsId 试题id") @RequestParam(value = "questionsId", required = true) String questionsId) {
        Map<String, Object> result = new HashMap<String, Object>();
        AccountDTO account = accountService.getUserByToken(token);
        if (account == null) {
            return new ResponseEntity<Object>(TokenUtil.tokenValid(),
                    HttpStatus.UNAUTHORIZED);
        }
        if (null == questionsId || "".equals(questionsId)) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "试题id不能为空");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        TaskQuestion questions = questionsService.findById(questionsId);
        if (null == questions) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.FALSE);
            result.put(ApiReturnConstants.ERROR, "试题不存在");
            return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
        }
        questions = questionsService.delQuestions(questions);
        result.put(ApiReturnConstants.DATA, questions.getId());
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }
}
